/****************************************************************************************************
Name:  LodhaGroupContactController ()
Copyright © 2012  Lodha Group
=====================================================================================================
=====================================================================================================
Purpose: 
-------
Visualforce page to replace standard web2lead page for web2lead in lodhagroup.com/contactus.php
=====================================================================================================
=====================================================================================================
History
-----------------------------------------------------------------------------------------------------
VERSION    AUTHOR                DATE             DETAIL              
1.0 -   CG Dev Team          02/04/2012      INITIAL DEVELOPMENT  
******************************************************************************************************/
public class LodhaGroupContactController {
    
    public String name {get;set;}
    public String email {get;set;}
    public String countryCode {get;set;}
    public String mobileNumber {get;set;}
    public String stdCode{get;set;}
    public String landLineNumber {get;set;}
    public String country {get;set;}
    public String city {get;set;}
    public String cityText {get;set;}
    public String uscitystate{get;set;}
    public String projectInterested {get;set;}
    public String campaignName {get;set;}
    public String publisher {get;set;}
    public String projectType {get;set;}
    public list<SelectOption> projectList {get;set;}
    public Boolean isinserted {get;set;}
    public string sourceofinformation{get;set;}
    
    private Map<Id,project_name__c> allProjects{get;set;}
    private String recordtypeid ;
    private String emailTemplateId ; 
    private String AdminEmailId ;
    private List<String> projectNames ; 
    String Error;
    Lead newlead;
    

    public LodhaGroupContactController(){
       
        try{
           
           
           campaignName= ApexPages.currentPage().getParameters().get('campaign');    //GET CAMPAIGN NAME FROM URL        
           publisher= ApexPages.currentPage().getParameters().get('publisher');      //GET PUBLISHER NAME FROM URL
                      
           getAllProjects();         //CREATE PROJECT MAP
           populateProjectList();    //DISPLAY PROJECT LIST 
           isinserted= false;
           

           /**** GET EMAIL TEMPLATE ID TO SEND AS AUTO-RESPONSE TO CAPTURED LEAD ****/
           emailTemplateId = [select id from EmailTemplate where developername=:WebToLeadPages__c.getInstance('LodhaGroup').Email_Template__c limit 1].Id;       
           AdminEmailId = WebToLeadPages__c.getInstance('LodhaGroup').Admin_Email__c;     
           this.country='India';       
        }
        catch(exception e){
            sendErrorMessage(e);
          system.debug('%%%message'+e.getmessage());  
        }
    }
    /*******************************************************************
        Purpose     : Populate the All ProjectNames in dropdown                        
        Parameters  : None
        Returns     : List of SelectOption of all ProjectName
    ********************************************************************/
    private void getAllProjects(){
    
        try{
            allProjects = new Map<Id,project_name__c>([select id,Name,Record_Type__c,Project_Type__c,City__c,Location__c from Project_name__c 
            where name!='Lodha Bellezza' AND name!='Unknown Project' AND name!='Generic' AND Isactive__c=true]);
            projectNames  = new List<String>();
            for(project_name__c project:allProjects.values()){
                projectNames.add(project.Name);
            }
            projectNames.sort();        
        }
        catch(exception e){
            sendErrorMessage(e);        
        }
    }
    
    private void populateProjectList(){
        try{
            projectList = new list<selectoption>();
            projectList.add(new selectoption('Select Project','Select Project'));
            String projectlabel='';
            if(allProjects!=null && !allProjects.isEmpty()){
                for(String str: projectNames){                
                    for(project_name__c project:allProjects.values()){   
                        if(str == project.Name){
                        projectlabel=project.Name;
                        if(project.Location__c!=''&&project.Location__c!=null)
                        {
                            projectlabel+=', '+project.Location__c;
                        }
                        if(project.City__c!=''&&project.City__c!=null)
                        {
                            projectlabel+=', '+project.City__c;
                        }
                            
                        
                            projectList.add(new selectoption(project.Id,projectlabel));                                                
                        }
                    }                
                }
            }
        }
        catch(exception e){
            sendErrorMessage(e);
        }
    }
              
    /*******************************************************************
        Purpose     : Save Lead                      
        Parameters  : None
        Returns     : None
    ********************************************************************/    
    public void submitLead(){
        try{
           
             newlead= new Lead(); 
         
            newlead.lastname = name;
            newlead.email = email;
            newlead.LeadSource = 'Web';            
            newlead.ISD_Code__c = CountryCode;
            newlead.STD_Code__c = stdCode;
            newlead.Campaign_Name__c=CampaignName;
            newlead.WebBanner_Source__c=publisher;
            
            if(projectInterested != null && projectInterested != '' && !allProjects.isEmpty()){
                recordtypeid = RecordTypeHelper.getRecordTypeId('Lead',allProjects.get(projectInterested).Record_Type__c);
                projectType =  allProjects.get(projectInterested).Project_Type__c.touppercase();
            }                        

            newlead.Recordtypeid = Recordtypeid;
            newlead.Project_Name__c = projectInterested;                         
            
            
            
            if(country == 'India'){
                newlead.Mobile__c = mobileNumber ;
                newlead.Phone = stdCode + landLineNumber;
                
                if(ProjectType=='COMMERCIAL'){    
                    newlead.Country_O__c = country;                
                    newlead.Office_Phone__c = stdCode+landLineNumber; 
                    newlead.Phone = '';
                    newlead.City_O__c=city;
                }
                else{
                    newlead.Country_R__c = country;
                    newlead.City_R__c = city;
                }
            }
            else{
            
             
             
                newlead.Mobile__c = CountryCode + mobileNumber ;
                newlead.Phone = CountryCode + stdCode + landLineNumber;              
                
                if(projectType == 'COMMERCIAL')
                {    newlead.City_O__c = 'Others';
                     newlead.Specify_Other_for_City_O__c = cityText;
                     newlead.Country_O__c = country;                
                     newlead.Office_Phone__c = CountryCode+stdCode+landLineNumber; 
                     newlead.Phone ='';  
                }
                
                else if(country == 'United States'){
                
               
                
                     newlead.City_R__c='Others';
                     newlead.Specify_Other_for_City_R__c =uscitystate;
                     newlead.Country_R__c = country;
                }else{
                     newlead.City_R__c='Others';
                     newlead.Specify_Other_for_City_R__c =cityText;
                     newlead.Country_R__c = country;  
                
                }
            }
           
            insert newlead;
              
            sendMailtoLead(emailTemplateId,newlead.Id);
            isinserted=true;            
        }catch(exception e){
        system.debug('## exception : '+e);
        
            Error=e.getmessage();  
              
            isinserted=false;            
        }
    }
   /*******************************************************************
        Purpose     : sendmail after lead is created                     
        Parameters  : None
        Returns     : None
    ********************************************************************/   
    private void sendMailtoLead(String templateId,String leadId){
        try{
       
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setTemplateId(emailTemplateId);         
            mail.setTargetObjectId(leadId);   
            mail.setSenderDisplayName('Lodha Group');
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });         
        }
        catch(exception e){
            sendErrorMessage(e);
        }
    }
   /**********************************************************************
        Purpose     : SendErrormail if there is an exception               
        Parameters  : None
        Returns     : None
    ***********************************************************************/
    public void sendErrorMessage(Exception e){
        try{
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAdd =  new String[]{'pradeep.kumar-l-g@capgemini.com'};
            mail.setToAddresses(toAdd);
            mail.setReplyTo('noreply@lodhagroup.com');
            mail.setSenderDisplayName('Lodha Group');
            mail.setSubject('Customer creation error');
            String htmlcontent;
            htmlcontent='<b>Exception:</b><br/>'+e+'<br/>';           
            mail.sethtmlbody(htmlcontent);
            mail.setBccSender(false);
            mail.setUseSignature(false);
            List<Messaging.SendEmailResult> results = Messaging.sendEmail(new Messaging.Email[]{ mail });
        }
        catch(Exception ex){
        
        }
    }  
    /************************************************************************
        Purpose     : SendErrormail if there is an error in inserting Lead                 
        Parameters  : None
        Returns     : None
    ***********************************************************************/
    public pagereference senderrmsg()
     {
     try{
     
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAdd =  new String[]{'pradeep.kumar-l-g@capgemini.com'};
            mail.setToAddresses(toAdd);
            mail.setReplyTo('noreply@lodhagroup.com');
            mail.setSenderDisplayName('Lodha Group');
            mail.setSubject('Customer creation error');
            String htmlcontent;
            if(Error==null || Error=='')
               Error ='';
            htmlcontent='<b>Exception:</b><br/>'+Error+'<br/><b>Lead Details:</b><br/>';
            htmlcontent+='<b>Name:</b>'+newlead.name+'<br/><b>Email Id:</b>'+newlead.email+'<br/>';
            htmlcontent+='<b>Mobile:</b>'+newlead.Mobile__c+'<br/><b>Landline:</b>'+newlead.phone+'<br/>';
            htmlcontent+='<b>stdCode:</b>'+stdCode+'<br/><b>country:</b>'+country+'<br/>';
            htmlcontent+='<b>city:</b>'+city+'<br/><b>citytext:</b>'+citytext+'<br/>';
            htmlcontent+='<b>CountryCode:</b>'+CountryCode+'<br/><b>Landline:</b>'+stdCode+newlead.phone+'<br/>';
            htmlcontent+='<b>Mobile:</b>'+newlead.Mobile__c+'<br/>';            
            htmlcontent+='<b>ProjectName:</b>'+projectInterested+'<br/><b>ProjectType:</b>'+ProjectType+'<br/>';            
            htmlcontent+='<b>Campaign name:</b>'+newlead.Campaign_Name__c+'<br/><b>Banner:</b>'+newlead.WebBanner_Source__c+'<br/>';            
            mail.sethtmlbody(htmlcontent);
            mail.setBccSender(false);
            mail.setUseSignature(false);
            List<Messaging.SendEmailResult> results = Messaging.sendEmail(new Messaging.Email[]{ mail });
            
            }
            catch(exception e)
            {}
            return null;
     }
   /************************************************************************
        Purpose     : Test Class                  
        Parameters  : None
        Returns     : None
    ***********************************************************************/
    static testmethod void testlodhaleadcapture()    
        {
        
        /*
         * Test record for country India and projectType is commercial
         */
           LodhaGroupContactController lodhagroup=new LodhaGroupContactController();
           lodhagroup.name='test';
           lodhagroup.email='test@test.com';
           lodhagroup.country='India';
           lodhagroup.city='Mumbai';
           lodhagroup.projectType='COMMERCIAL';
           lodhagroup.mobileNumber='14725836954';          
           lodhagroup.projectInterested='Casa Bella';
           lodhagroup.submitLead();
           
           
           
           /*
            * Test record for country India and projecttype Non commercial
            */
            
           LodhaGroupContactController lodhagroup1=new LodhaGroupContactController();
           lodhagroup1.name='test';
           lodhagroup1.email='test@test.com';
           lodhagroup1.country='India';
           lodhagroup1.city='Mumbai';
           lodhagroup1.projectType='residential';
           lodhagroup1.mobileNumber='14725836954';
           lodhagroup1.submitLead();
           lodhagroup1.senderrmsg();
           
           
           /*
            * Test record for country Non India and projectType is commercial
            */
           LodhaGroupContactController lodhagroup2=new LodhaGroupContactController();
           lodhagroup2.name='test';
           lodhagroup2.email='test@test.com';
           lodhagroup2.country='France';
           lodhagroup2.city='test';
           lodhagroup2.projectType='COMMERCIAL';
           lodhagroup2.mobileNumber='14725836954';
           lodhagroup2.submitLead();
           
           /*
            * Test record for country  Non India and projectType Non commercial
            */
           LodhaGroupContactController lodhagroup3=new LodhaGroupContactController();
           lodhagroup3.name='test';
           lodhagroup3.email='test@test.com';
           lodhagroup3.country='France';
           lodhagroup3.city='Test';
           lodhagroup3.projectType='residential';
           lodhagroup3.mobileNumber='14725836954';
           lodhagroup3.submitLead();
        }
   
}